<template>
    <div id="app" class="containers">
        <header class="header">
            <span class="icon-container"><i class="el-icon-message-solid"></i></span>
            <span class="scrolling-text">欢迎光临种花吧商城，存在更多实惠花种，更多详细内容优惠卷请前往活动页面进行了解</span>
        </header>
        <main class="content">
            <div class="product-containers">
                <div class="product-image-wrapper">
                    <div class="product-image-zoom">
                        <img :src="flowerDatas.flowerPhoto" alt="Product Image" class="product-image-main">
                        <div class="zoom-pane"></div>
                    </div>
                    <div class="product-image-magnifier">
                        <img :src="flowerDatas.flowerPhoto" alt="Magnified Product Image" class="magnified-image">
                    </div>
                    <div class="thumbnail-list">
                        <div class="thumbnail-item" v-for="i in 4" :key="i">
                            <img :src="flowerDatas.flowerPhoto" alt="Thumbnail">
                        </div>
                    </div>
                </div>
                <div class="product-info">
                    <div class="product-title">
                        <h1>{{ flowerDatas.name }}</h1>
                        <div class="product-tags">
                            <el-tag type="success" effect="dark">{{ flowerDatas.menaning }}</el-tag>
                            <el-tag type="warning">{{ flowerDatas.season }}</el-tag>
                            <el-tag>{{ flowerDatas.category }}</el-tag>
                            <el-tag type="info">{{ flowerDatas.color }}</el-tag>
                        </div>
                    </div>
                    <div class="product-price">
                        <div class="price-label">价格</div>
                        <div class="price-value">¥{{ flowerDatas.price }}</div>
                        <div class="price-info">
                            <span class="original-price">¥{{ flowerDatas.price * 1.2 }}</span>
                            <span class="discount">已优惠{{ (flowerDatas.price * 0.2).toFixed(2) }}元</span>
                            <span class="price-notify"><a href="#">降价通知</a></span>
                        </div>
                    </div>
                    <div class="product-description">
                        <h3>商品介绍</h3>
                        <p>{{ flowerDatas.introduction }}</p>
                    </div>
                    <div class="product-actions">
                        <el-button type="danger" size="large" @click="addflower(flowerDatas.flowerId)">
                            <i class="el-icon-shopping-cart-2"></i> 加入购物车
                        </el-button>
                        <el-button type="danger" size="large" @click="go(flowerDatas.flowerId)">
                            <i class="el-icon-shopping-bag-1"></i> 立即购买
                        </el-button>
                    </div>
                </div>
            </div>
            <div class="product-detail">
                <el-tabs v-model="activeTab" type="border-card">
                    <el-tab-pane label="商品详情" name="detail">
                        <div class="detail-content">
                            <div v-for="i in 5" :key="i" class="detail-item">
                                <p>{{ flowerDatas.introduction }}</p>
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="种植经验" name="experience">
                        <div class="experience-section">
                            <div class="experience-form" v-if="isAuthenticated">
                                <h3>分享您的种植经验</h3>
                                <el-form :model="experienceForm" :rules="experienceRules" ref="experienceForm">
                                    <el-form-item label="经验标题" prop="title">
                                        <el-input v-model="experienceForm.title" placeholder="请输入标题"></el-input>
                                    </el-form-item>
                                    <el-form-item label="种植心得" prop="content">
                                        <el-input type="textarea" v-model="experienceForm.content" 
                                            :rows="4" placeholder="请分享您的种植经验和建议"></el-input>
                                    </el-form-item>
                                    <el-form-item label="上传图片" prop="images">
                                        <div class="experience-uploader">
                                            <el-upload
                                                class="upload-demo"
                                                action="http://localhost:9090/api/file/upload"
                                                :headers="headers"
                                                :data="uploadData"
                                                :show-file-list="false"
                                                :on-success="handleImageSuccess"
                                                :on-error="handleUploadError"
                                                :before-upload="beforeImageUpload">
                                                <img v-if="experienceForm.images.length > 0" 
                                                     :src="experienceForm.images[0]" 
                                                     class="experience-image">
                                                <i v-else class="el-icon-plus experience-uploader-icon"></i>
                                                <div class="el-upload__tip">支持 jpg、jpeg、png 格式，大小不超过 5MB</div>
                                            </el-upload>
                                        </div>
                                    </el-form-item>
                                    <el-form-item>
                                        <el-button type="primary" @click="submitExperience">分享经验</el-button>
                                    </el-form-item>
                                </el-form>
                            </div>
                            <div v-else class="login-prompt">
                                <p>请<el-button type="text" @click="$router.push('/login')">登录</el-button>后分享您的种植经验</p>
                            </div>
                            
                            <div class="experience-list">
                                <div v-for="(exp, index) in experiences" :key="index" class="experience-item">
                                    <div class="experience-content">
                                        <img :src="exp.imageUrl" :alt="exp.title" class="experience-photo">
                                        <div class="experience-info">
                                            <h4>{{ exp.title }}</h4>
                                            <p>{{ exp.content }}</p>
                                            <div class="experience-meta">
                                                <span class="author">
                                                    <i class="el-icon-user"></i>
                                                    {{ exp.userName }}
                                                </span>
                                                <span class="time">
                                                    <i class="el-icon-time"></i>
                                                    {{ exp.createTime }}
                                                </span>
                                                <div class="experience-actions">
                                                    <el-button type="text" @click="likeExperience(exp.id)">
                                                        <i class="el-icon-star-off"></i>
                                                        点赞 ({{ exp.likes }})
                                                    </el-button>
                                                    <el-button type="text" @click="replyExperience()">
                                                        <i class="el-icon-chat-dot-round"></i>
                                                        回复
                                                    </el-button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="商品评价" name="reviews">
                        <div class="comment-section">
                            <div class="comment-form">
                                <textarea placeholder="请输入您的评价..." v-model="Commentcontent"></textarea>
                                <el-button type="primary" @click="addComment">提交评价</el-button>
                            </div>
                            <div class="comment-list">
                                <div class="comment-item" v-for="(comment, index) in comments" :key="index">
                                    <div class="comment-header">
                                        <img :src="flowerDatas.flowerPhoto" alt="User Avatar" class="user-avatar">
                                        <div class="user-info">
                                            <span class="username">{{ comment.userId }}</span>
                                            <span class="time">{{ comment.createdAt }}</span>
                                        </div>
                                    </div>
                                    <div class="comment-content">
                                        <p>{{ comment.content }}</p>
                                    </div>
                                    <div class="comment-actions">
                                        <el-button type="text" icon="el-icon-message">回复</el-button>
                                        <el-button type="text" icon="el-icon-star-off">收藏</el-button>
                                        <el-button type="text" icon="el-icon-edit">编辑</el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </main>
    </div>
</template>

<script>
import { uploadRequest } from '@/router/request'

export default {
    props: ['id'],
    data() {
        return {
            radio: '1',
            reviews: ['评论1', '评论2', '评论3'],
            flowerDatas: {},
            comments: [],
            newComment: {},
            Commentcontent: '',
            activeTab: 'detail',
            isAuthenticated: false,
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            uploadData: {
                type: 'image'
            },
            experienceForm: {
                title: '',
                content: '',
                images: []
            },
            experienceRules: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                ],
                content: [
                    { required: true, message: '请输入种植心得', trigger: 'blur' },
                    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
                ]
            },
            experiences: [],
        }
    },
    created() {
        this.checkAuth();
        this.fetchExperiences();
        this.fetchPostDetail();
    },
    methods: {
        addflower(flowerId) {
            // 使用模板字符串构建URL，并确保路径参数正确传递
            this.request.post(`/cartitems/addCart/${flowerId}`).then(res => {
                console.log(res);
                if (res.code == '1') {
                    this.$message.success(res.data);
                } else {
                    this.$message.error('加入购物车失败');
                }
            }).catch(error => {
                console.error('请求失败:', error);
                this.$message.error('请求失败，请稍后再试');
            });
        },
        go() {
            // 构造直接购买的商品信息
            const buyNowInfo = {
                items: [{
                    itemId: this.flowerDatas.flowerId,
                    name: this.flowerDatas.name,
                    price: this.flowerDatas.price,
                    quantity: 1,
                    image: this.flowerDatas.flowerPhoto,
                    spec: this.flowerDatas.category,
                    totalPrice: this.flowerDatas.price
                }],
                totalAmount: this.flowerDatas.price,
                itemCount: 1,
                type: 'buyNow' // 标记这是直接购买而不是购物车结算
            };

            // 存储到 localStorage
            localStorage.setItem('checkoutInfo', JSON.stringify(buyNowInfo));
            
            // 跳转到结算页面
            this.$router.push("/balance");
        },
        addComment() {
            console.log( this.Commentcontent);
            
    // 发送请求添加评论
    this.request.post(`/flowercomment/${this.id}`, this.Commentcontent)
      .then(response => {
        // 请求成功后的逻辑
        console.log('评论添加成功:', response.data);
        this.successMessage = '评论添加成功！';

        // 刷新评论列表
        this.fetchComments();
      })
      .catch(error => {
        // 请求失败后的逻辑
        console.error('添加评论失败:', error);
        this.errorMessage = '添加评论时出现错误，请稍后再试。';
      });
  },
  fetchComments() {
    this.request.get(`/flowercomment/${this.id}`)
      .then(response => {
        this.comments = response.data;
        console.log(this.comments);
        
      })
      .catch(error => {
        console.error('获取评论列表失败:', error);
      });
  },

        fetchPostDetail() {
            console.log('Received ID:', this.id); // 添加日志来验证ID是否正确传递
            this.request.get(`/flowers/${this.id}`).then(res => {
                console.log(res);
                this.fetchComments();
                this.flowerDatas = res.data;
            })
        },
        handleImageSuccess(res) {
            if (res.code === 1 && res.data) {
                this.experienceForm.images.push(res.data);
                this.$message.success('图片上传成功');
            } else {
                this.$message.error('图片上传失败');
            }
        },
        handleUploadError(err) {
            console.error('上传失败:', err);
            this.$message.error('图片上传失败，请重试');
        },
        beforeImageUpload(file) {
            const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt5M = file.size / 1024 / 1024 < 5;

            if (!isJPGOrPNG) {
                this.$message.error('只能上传JPG/PNG格式的图片！');
                return false;
            }
            if (!isLt5M) {
                this.$message.error('图片大小不能超过5MB！');
                return false;
            }
            return true;
        },
        async submitExperience() {
            try {
                await this.$refs.experienceForm.validate();
                const response = await this.request.post(`/flower-experience/${this.id}`, {
                    title: this.experienceForm.title,
                    content: this.experienceForm.content,
                    images: this.experienceForm.images
                });
                
                if (response.code === 1) {
                    this.$message.success('经验分享成功！');
                    this.fetchExperiences();
                    this.resetExperienceForm();
                } else {
                    this.$message.error(response.msg || '分享失败');
                }
            } catch (error) {
                console.error('分享经验失败:', error);
                this.$message.error('分享失败，请重试');
            }
        },
        resetExperienceForm() {
            this.experienceForm = {
                title: '',
                content: '',
                images: []
            };
            this.$refs.experienceForm.resetFields();
        },
        async fetchExperiences() {
            try {
                const response = await this.request.get(`/flower-experience/${this.id}`);
                if (response.code === 1) {
                    this.experiences = response.data;
                }
            } catch (error) {
                console.error('获取种植经验列表失败:', error);
            }
        },
        async likeExperience(experienceId) {
            if (!this.isAuthenticated) {
                this.$message.warning('请先登录');
                return;
            }
            try {
                const response = await this.request.post(`/flower-experience/like/${experienceId}`);
                if (response.code === 1) {
                    this.fetchExperiences();
                }
            } catch (error) {
                console.error('点赞失败:', error);
            }
        },
        replyExperience() {
            if (!this.isAuthenticated) {
                this.$message.warning('请先登录');
                return;
            }
            // 实现回复功能
            this.$message.info('回复功能开发中...');
        },
        checkAuth() {
            // 检查用户是否登录
            const token = localStorage.getItem('token');
            this.isAuthenticated = !!token;
        }
    },
    mounted() {
        this.$nextTick(() => {
            const zoomPane = document.querySelector('.zoom-pane');
            const magnifier = document.querySelector('.product-image-magnifier');
            const mainImage = document.querySelector('.product-image-main');
            const magnifiedImage = document.querySelector('.magnified-image');

            const zoomRatio = 2;

            mainImage.addEventListener('mousemove', (event) => {
                const rect = mainImage.getBoundingClientRect();
                const x = event.clientX - rect.left;
                const y = event.clientY - rect.top;

                // 计算放大镜的位置，使其中心对准鼠标位置
                const zoomPaneX = x - zoomPane.offsetWidth / 2;
                const zoomPaneY = y - zoomPane.offsetHeight / 2;

                // 限制放大镜不超出图片边界
                const maxX = mainImage.offsetWidth - zoomPane.offsetWidth;
                const maxY = mainImage.offsetHeight - zoomPane.offsetHeight;
                
                const boundedX = Math.max(0, Math.min(maxX, zoomPaneX));
                const boundedY = Math.max(0, Math.min(maxY, zoomPaneY));

                // 设置放大镜位置
                zoomPane.style.left = `${boundedX}px`;
                zoomPane.style.top = `${boundedY}px`;

                // 计算放大图片的位置
                const magnifiedX = -boundedX * zoomRatio;
                const magnifiedY = -boundedY * zoomRatio;

                // 设置放大图片位置
                magnifiedImage.style.transform = `translate(${magnifiedX}px, ${magnifiedY}px)`;
            });

            // 鼠标进入图片区域时显示放大镜
            mainImage.addEventListener('mouseenter', () => {
                magnifier.style.display = 'block';
                zoomPane.style.display = 'block';
            });

            // 鼠标离开图片区域时隐藏放大镜
            mainImage.addEventListener('mouseleave', () => {
                magnifier.style.display = 'none';
                zoomPane.style.display = 'none';
            });

            // 添加鼠标移动时的平滑效果
            let isMoving = false;
            let moveTimeout;

            mainImage.addEventListener('mousemove', () => {
                if (!isMoving) {
                    isMoving = true;
                }
                clearTimeout(moveTimeout);
                moveTimeout = setTimeout(() => {
                    isMoving = false;
                }, 100);
            });
        });
    }
}
</script>

<style scoped>
.containers {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    background: #fff;
}

.header {
    background: #f5f5f5;
    padding: 10px 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    overflow: hidden;
    position: relative;
}

.icon-container {
    color: red;
    margin-right: 10px;
    flex-shrink: 0;
}

.scrolling-text {
    display: inline-block;
    white-space: nowrap;
    animation: scrollText 20s linear infinite;
}

@keyframes scrollText {
    0% {
        transform: translateX(0);
    }
    100% {
        transform: translateX(calc(100% - 40px));
    }
}

.product-containers {
    display: flex;
    gap: 40px;
    margin-bottom: 40px;
}

.product-image-wrapper {
    width: 400px;
    position: relative;
}

.product-image-zoom {
    position: relative;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    overflow: hidden;
    width: 100%;
    height: 400px;
}

.product-image-main {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.zoom-pane {
    position: absolute;
    top: 0;
    left: 0;
    width: 200px;
    height: 200px;
    background-color: rgba(255, 255, 255, 0.5);
    border: 1px solid #ddd;
    pointer-events: none; /* 移除鼠标事件 */
    display: none;
}

.product-image-magnifier {
    position: absolute;
    top: 0;
    left: 420px;
    width: 400px;
    height: 400px;
    border: 1px solid #ddd;
    background-color: #fff;
    overflow: hidden;
    display: none;
    z-index: 1000;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

.magnified-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 800px;
    height: 800px;
    object-fit: cover;
}

.thumbnail-list {
    display: flex;
    gap: 10px;
    margin-top: 10px;
}

.thumbnail-item {
    width: 80px;
    height: 80px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    overflow: hidden;
    cursor: pointer;
}

.thumbnail-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-info {
    flex: 1;
}

.product-title h1 {
    font-size: 24px;
    color: #333;
    margin-bottom: 15px;
}

.product-tags {
    margin-bottom: 20px;
}

.product-price {
    background: #f5f5f5;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
}

.price-label {
    color: #666;
    font-size: 14px;
    margin-bottom: 5px;
}

.price-value {
    color: #e4393c;
    font-size: 28px;
    font-weight: bold;
    margin-bottom: 5px;
}

.price-info {
    color: #999;
    font-size: 12px;
}

.original-price {
    text-decoration: line-through;
    margin-right: 10px;
}

.discount {
    color: #e4393c;
    margin-right: 10px;
}

.product-description {
    margin-bottom: 30px;
}

.product-description h3 {
    font-size: 16px;
    color: #333;
    margin-bottom: 10px;
}

.product-description p {
    color: #666;
    line-height: 1.6;
}

.product-actions {
    display: flex;
    gap: 20px;
}

.product-actions .el-button {
    padding: 12px 30px;
    font-size: 16px;
}

.product-detail {
    margin-top: 40px;
}

.detail-content {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
}

.comment-section {
    padding: 20px;
}

.comment-form {
    margin-bottom: 30px;
}

.comment-form textarea {
    width: 100%;
    height: 100px;
    padding: 10px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    margin-bottom: 10px;
    resize: none;
}

.comment-item {
    padding: 20px;
    border-bottom: 1px solid #e0e0e0;
}

.comment-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
}

.user-info {
    display: flex;
    flex-direction: column;
}

.username {
    font-weight: bold;
    color: #333;
}

.time {
    color: #999;
    font-size: 12px;
}

.comment-content {
    color: #666;
    line-height: 1.6;
    margin-bottom: 10px;
}

.comment-actions {
    display: flex;
    gap: 15px;
}

.experience-section {
    padding: 20px;
}

.experience-form {
    margin-bottom: 30px;
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
}

.experience-form h3 {
    margin-bottom: 20px;
    color: #333;
    font-size: 18px;
}

.experience-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
}

.experience-uploader:hover {
    border-color: #409EFF;
}

.experience-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.experience-image {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
}

.experience-list {
    margin-top: 20px;
}

.experience-item {
    padding: 20px;
    border-bottom: 1px solid #eee;
    transition: all 0.3s ease;
}

.experience-item:hover {
    background: #f8f9fa;
}

.experience-content {
    display: flex;
    gap: 20px;
}

.experience-photo {
    width: 200px;
    height: 150px;
    object-fit: cover;
    border-radius: 8px;
}

.experience-info {
    flex: 1;
}

.experience-info h4 {
    margin: 0 0 10px;
    color: #333;
    font-size: 16px;
}

.experience-info p {
    color: #666;
    line-height: 1.6;
    margin-bottom: 15px;
}

.experience-meta {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #999;
    font-size: 14px;
}

.experience-meta span {
    display: flex;
    align-items: center;
    gap: 5px;
}

.experience-actions {
    display: flex;
    gap: 15px;
}

.login-prompt {
    text-align: center;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
    margin-bottom: 20px;
}

.login-prompt p {
    color: #666;
}

@media (max-width: 768px) {
    .product-containers {
        flex-direction: column;
    }
    
    .product-image-wrapper {
        width: 100%;
    }
    
    .product-info {
        width: 100%;
    }
    .experience-content {
        flex-direction: column;
    }
    
    .experience-photo {
        width: 100%;
        height: 200px;
    }
}
</style>